'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { formatAddress, formatDate, formatCurrency } from '@/lib/utils';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { Search, Coins, TrendingUp, TrendingDown, ArrowUpDown, Eye, Settings, DollarSign } from 'lucide-react';
import { ExchangeRateManager } from '@/components/dtvc/exchange-rate-manager';

interface DTVCBalance {
  id: string;
  user_id: string;
  wallet_address: string;
  balance: number;
  total_earned: number;
  total_spent: number;
  total_exchanged: number;
  updated_at: string;
}

interface DTVCTransaction {
  id: string;
  user_id: string;
  wallet_address: string;
  transaction_type: string;
  amount: number;
  balance_before: number;
  balance_after: number;
  source: string;
  description: string;
  created_at: string;
}

interface DTVCStats {
  total_balances: number;
  total_dtvc_in_circulation: number;
  total_earned: number;
  total_spent: number;
  total_exchanged: number;
  active_users: number;
  exchange_rate: number;
  avg_balance: number;
}

interface ExchangeSettings {
  dtvc_to_dtv_rate: number;
  min_exchange_amount: number;
  max_exchange_amount: number;
  exchange_fee_percentage: number;
  is_exchange_enabled: boolean;
}

export default function DTVCPage() {
  const { currentChain } = useChain();
  const [searchTerm, setSearchTerm] = useState('');
  const [transactionTypeFilter, setTransactionTypeFilter] = useState<string>('all');
  const [selectedUser, setSelectedUser] = useState<string | null>(null);
  const [showSettings, setShowSettings] = useState(false);
  const [showTransactions, setShowTransactions] = useState(false);
  const [activeTab, setActiveTab] = useState<'balances' | 'transactions' | 'exchange-rates'>('balances');

  // Fetch DTVC stats
  const { data: stats } = useQuery<DTVCStats>({
    queryKey: ['dtvc-stats', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/dtvc/admin/stats');
      return response.data;
    },
    refetchInterval: 30000,
  });

  // Fetch DTVC balances
  const { data: balances, isLoading } = useQuery<DTVCBalance[]>({
    queryKey: ['dtvc-balances', searchTerm, currentChain],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (searchTerm) params.append('search', searchTerm);
      
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(`/api/v1/dtvc/admin/balances?${params}`);
      return response.data;
    },
    refetchInterval: 30000,
  });

  // Fetch DTVC transactions
  const { data: transactions } = useQuery<DTVCTransaction[]>({
    queryKey: ['dtvc-transactions', transactionTypeFilter, selectedUser, currentChain],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (transactionTypeFilter !== 'all') params.append('type', transactionTypeFilter);
      if (selectedUser) params.append('user', selectedUser);
      
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(`/api/v1/dtvc/admin/transactions?${params}`);
      return response.data;
    },
    refetchInterval: 30000,
    enabled: showTransactions,
  });

  // Fetch exchange settings
  const { data: exchangeSettings, refetch: refetchSettings } = useQuery<ExchangeSettings>({
    queryKey: ['exchange-settings', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/dtvc/admin/settings');
      return response.data;
    },
    enabled: showSettings,
  });

  const handleUpdateSettings = async (settings: Partial<ExchangeSettings>) => {
    try {
      const client = multiChainApi.getClient(currentChain);
      await client.put('/api/v1/dtvc/admin/settings', settings);
      refetchSettings();
    } catch (error) {
      console.error('Error updating settings:', error);
    }
  };

  const filteredBalances = balances?.filter(balance => {
    return !searchTerm || 
      balance.wallet_address.toLowerCase().includes(searchTerm.toLowerCase());
  }) || [];

  const getTransactionTypeColor = (type: string) => {
    switch (type) {
      case 'earn': return 'bg-green-100 text-green-800';
      case 'spend': return 'bg-red-100 text-red-800';
      case 'exchange': return 'bg-blue-100 text-blue-800';
      case 'admin': return 'bg-purple-100 text-purple-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getTransactionIcon = (type: string) => {
    switch (type) {
      case 'earn': return <TrendingUp className="h-3 w-3" />;
      case 'spend': return <TrendingDown className="h-3 w-3" />;
      case 'exchange': return <ArrowUpDown className="h-3 w-3" />;
      default: return <Coins className="h-3 w-3" />;
    }
  };

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="space-y-6">
        {/* Header */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold tracking-tight">DTVC Management</h1>
            <p className="text-muted-foreground">
              Manage DTV Credits and exchange system
            </p>
          </div>
          <div className="flex gap-2">
            <Button
              variant="outline"
              onClick={() => setShowSettings(!showSettings)}
            >
              <Settings className="h-4 w-4 mr-2" />
              Exchange Settings
            </Button>
          </div>
        </div>

        {/* Stats Cards */}
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total DTVC in Circulation</CardTitle>
              <Coins className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(stats?.total_dtvc_in_circulation || 0, 'DTVC')}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Active Users</CardTitle>
              <TrendingUp className="h-4 w-4 text-green-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">{stats?.active_users || 0}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Exchanged</CardTitle>
              <ArrowUpDown className="h-4 w-4 text-blue-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(stats?.total_exchanged || 0, 'DTVC')}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Average Balance</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(stats?.avg_balance || 0, 'DTVC')}</div>
            </CardContent>
          </Card>
        </div>

        {/* Exchange Settings */}
        {showSettings && exchangeSettings && (
          <Card>
            <CardHeader>
              <CardTitle>Exchange Settings</CardTitle>
              <CardDescription>Configure DTVC to DTV exchange parameters</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                <div>
                  <label className="text-sm font-medium">Exchange Rate</label>
                  <div className="text-2xl font-bold">
                    {exchangeSettings.dtvc_to_dtv_rate} DTVC = 1 DTV
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium">Min Exchange</label>
                  <div className="text-lg font-medium">
                    {formatCurrency(exchangeSettings.min_exchange_amount, 'DTVC')}
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium">Max Exchange</label>
                  <div className="text-lg font-medium">
                    {formatCurrency(exchangeSettings.max_exchange_amount, 'DTVC')}
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium">Exchange Status</label>
                  <div className={`text-sm font-medium ${
                    exchangeSettings.is_exchange_enabled ? 'text-green-600' : 'text-red-600'
                  }`}>
                    {exchangeSettings.is_exchange_enabled ? 'Enabled' : 'Disabled'}
                  </div>
                </div>
              </div>
              <div className="flex gap-2 mt-4">
                <Button
                  size="sm"
                  onClick={() => handleUpdateSettings({ 
                    is_exchange_enabled: !exchangeSettings.is_exchange_enabled 
                  })}
                  variant={exchangeSettings.is_exchange_enabled ? "danger" : "primary"}
                >
                  {exchangeSettings.is_exchange_enabled ? 'Disable' : 'Enable'} Exchange
                </Button>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Tab Navigation */}
        <div className="flex space-x-1 bg-muted p-1 rounded-lg w-fit">
          <Button
            variant={activeTab === 'balances' ? "primary" : "ghost"}
            size="sm"
            onClick={() => {
              setActiveTab('balances');
              setShowTransactions(false);
            }}
          >
            <Coins className="h-4 w-4 mr-2" />
            User Balances
          </Button>
          <Button
            variant={activeTab === 'transactions' ? "primary" : "ghost"}
            size="sm"
            onClick={() => {
              setActiveTab('transactions');
              setShowTransactions(true);
            }}
          >
            <ArrowUpDown className="h-4 w-4 mr-2" />
            Transactions
          </Button>
          <Button
            variant={activeTab === 'exchange-rates' ? "primary" : "ghost"}
            size="sm"
            onClick={() => {
              setActiveTab('exchange-rates');
              setShowTransactions(false);
            }}
          >
            <DollarSign className="h-4 w-4 mr-2" />
            Exchange Rates
          </Button>
        </div>

        {activeTab === 'balances' ? (
          // User Balances
          <Card>
            <CardHeader>
              <CardTitle>User DTVC Balances</CardTitle>
              <CardDescription>All user DTVC balances and activity</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex flex-col sm:flex-row gap-4 mb-6">
                <div className="flex-1 relative">
                  <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                  <input
                    type="text"
                    placeholder="Search by wallet address..."
                    className="w-full pl-10 pr-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                  />
                </div>
              </div>

              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="text-left p-4">Wallet Address</th>
                      <th className="text-left p-4">Current Balance</th>
                      <th className="text-left p-4">Total Earned</th>
                      <th className="text-left p-4">Total Spent</th>
                      <th className="text-left p-4">Total Exchanged</th>
                      <th className="text-left p-4">Last Updated</th>
                      <th className="text-left p-4">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {isLoading ? (
                      <tr>
                        <td colSpan={7} className="text-center p-8">
                          Loading balances...
                        </td>
                      </tr>
                    ) : filteredBalances.length === 0 ? (
                      <tr>
                        <td colSpan={7} className="text-center p-8 text-muted-foreground">
                          No balances found
                        </td>
                      </tr>
                    ) : (
                      filteredBalances.map((balance) => (
                        <tr key={balance.id} className="border-b hover:bg-muted/50">
                          <td className="p-4">
                            <div className="font-mono text-sm">
                              {formatAddress(balance.wallet_address)}
                            </div>
                          </td>
                          <td className="p-4">
                            <div className="font-bold text-lg">
                              {formatCurrency(balance.balance, 'DTVC')}
                            </div>
                          </td>
                          <td className="p-4 text-green-600 font-medium">
                            {formatCurrency(balance.total_earned, 'DTVC')}
                          </td>
                          <td className="p-4 text-red-600 font-medium">
                            {formatCurrency(balance.total_spent, 'DTVC')}
                          </td>
                          <td className="p-4 text-blue-600 font-medium">
                            {formatCurrency(balance.total_exchanged, 'DTVC')}
                          </td>
                          <td className="p-4 text-sm text-muted-foreground">
                            {formatDate(balance.updated_at)}
                          </td>
                          <td className="p-4">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => {
                                setSelectedUser(balance.wallet_address);
                                setShowTransactions(true);
                              }}
                            >
                              <Eye className="h-3 w-3 mr-1" />
                              View
                            </Button>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        ) : activeTab === 'transactions' ? (
          // Transactions
          <Card>
            <CardHeader>
              <div className="flex justify-between items-center">
                <div>
                  <CardTitle>DTVC Transactions</CardTitle>
                  <CardDescription>
                    {selectedUser ? `Transactions for ${formatAddress(selectedUser)}` : 'All DTVC transactions'}
                  </CardDescription>
                </div>
                {selectedUser && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setSelectedUser(null)}
                  >
                    Show All
                  </Button>
                )}
              </div>
            </CardHeader>
            <CardContent>
              <div className="flex flex-col sm:flex-row gap-4 mb-6">
                <select
                  className="px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  value={transactionTypeFilter}
                  onChange={(e) => setTransactionTypeFilter(e.target.value)}
                >
                  <option value="all">All Types</option>
                  <option value="earn">Earn</option>
                  <option value="spend">Spend</option>
                  <option value="exchange">Exchange</option>
                  <option value="admin">Admin</option>
                </select>
              </div>

              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="text-left p-4">Type</th>
                      <th className="text-left p-4">Wallet Address</th>
                      <th className="text-left p-4">Amount</th>
                      <th className="text-left p-4">Balance Before</th>
                      <th className="text-left p-4">Balance After</th>
                      <th className="text-left p-4">Source</th>
                      <th className="text-left p-4">Date</th>
                    </tr>
                  </thead>
                  <tbody>
                    {transactions && transactions.length > 0 ? (
                      transactions.map((transaction) => (
                        <tr key={transaction.id} className="border-b hover:bg-muted/50">
                          <td className="p-4">
                            <div className="flex items-center gap-2">
                              <span className={`flex items-center gap-1 px-2 py-1 rounded text-sm ${
                                getTransactionTypeColor(transaction.transaction_type)
                              }`}>
                                {getTransactionIcon(transaction.transaction_type)}
                                {transaction.transaction_type}
                              </span>
                            </div>
                          </td>
                          <td className="p-4">
                            <div className="font-mono text-sm">
                              {formatAddress(transaction.wallet_address)}
                            </div>
                          </td>
                          <td className="p-4">
                            <div className={`font-medium ${
                              transaction.transaction_type === 'earn' ? 'text-green-600' :
                              transaction.transaction_type === 'spend' ? 'text-red-600' :
                              'text-blue-600'
                            }`}>
                              {transaction.transaction_type === 'spend' ? '-' : '+'}
                              {formatCurrency(transaction.amount, 'DTVC')}
                            </div>
                          </td>
                          <td className="p-4">
                            {formatCurrency(transaction.balance_before, 'DTVC')}
                          </td>
                          <td className="p-4">
                            {formatCurrency(transaction.balance_after, 'DTVC')}
                          </td>
                          <td className="p-4">
                            <div className="text-sm">
                              <div className="font-medium">{transaction.source}</div>
                              {transaction.description && (
                                <div className="text-muted-foreground">{transaction.description}</div>
                              )}
                            </div>
                          </td>
                          <td className="p-4 text-sm text-muted-foreground">
                            {formatDate(transaction.created_at)}
                          </td>
                        </tr>
                      ))
                    ) : (
                      <tr>
                        <td colSpan={7} className="text-center p-8 text-muted-foreground">
                          No transactions found
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        ) : (
          // Exchange Rate Management
          <ExchangeRateManager />
        )}
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
}